<template>
  <div class="subtitle-request-tab-container">
    <!-- 左侧面板：影视剧选择 -->
    <div class="panel-section left-panel">
      <DramaListPanel @drama-selected="handleDramaSelected" />
    </div>

    <!-- 分割线 -->
    <div class="panel-divider"></div>

    <!-- 中间面板：剧集列表 -->
    <div class="panel-section middle-panel">
      <EpisodeListPanel 
        :selected-drama="selectedDrama"
        :episodes="episodes"
        :loading-episodes="loadingEpisodes"
        @episode-selected="handleEpisodeSelected"
        @episodes-selected="handleEpisodesSelected"
      />
    </div>

    <!-- 分割线 -->
    <div class="panel-divider"></div>

    <!-- 右侧面板：字幕请求表单 -->
    <div class="panel-section right-panel">
      <SubtitleFormPanel 
        :selected-drama="selectedDrama"
        :episodes="episodes"
        :loading-episodes="loadingEpisodes"
        :available-languages="availableLanguages"
        @submit-request="handleSubmitRequest"
        @submit-request-for-entire-drama="handleSubmitRequestForEntireDrama"
        @request-submitted="handleRequestSubmitted"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useSubtitleRequestStore } from '../../stores/subtitleRequest'
import DramaListPanel from './DramaListPanel.vue'
import EpisodeListPanel from './EpisodeListPanel.vue'
import SubtitleFormPanel from './SubtitleFormPanel.vue'
import type { Drama, Episode, LanguageOption } from '../../api/drama'
import { createProject, batchCreateProjects, type BatchCreateProjectItem } from '../../api/projects'
import { requestManager } from '../../utils/requestManager'

const store = useSubtitleRequestStore()

// Props from parent
const props = defineProps({
  loadingDramas: {
    type: Boolean,
    default: false,
  },
  selectedDrama: {
    type: Object as () => Drama | null,
    default: null,
  },
  episodes: {
    type: Array as () => Episode[],
    required: true,
  },
  loadingEpisodes: {
    type: Boolean,
    default: false,
  },
  availableLanguages: {
    type: Array as () => LanguageOption[],
    required: true,
  },
})

const emit = defineEmits([
  'drama-selected',
  'fetch-episodes',
  'submit-request',
  'submit-request-for-entire-drama',
  'request-submitted'
])

// Event handlers
const handleDramaSelected = (drama: Drama | null) => {
  store.setSelectedDrama(drama)
  emit('drama-selected', drama)
  if (drama) {
    emit('fetch-episodes', drama.id)
  }
}

const handleEpisodeSelected = (episode: Episode | null) => {
  store.setSelectedEpisode(episode)
}

const handleEpisodesSelected = (episodes: Episode[]) => {
  store.setSelectedEpisodes(episodes)
}

const handleRequestSubmitted = () => {
  store.clearSelection()
  emit('request-submitted')
}

// Request handling
const handleBatchProjectCreation = async (episodes: Episode[], languages: string[]) => {
  if (!episodes.length) {
    ElMessage.warning('没有可创建的剧集');
    return;
  }

  if (!languages.length) {
    ElMessage.warning('请至少选择一种语言');
    return;
  }

  const loadingMessage = ElMessage({
    message: `正在批量创建 ${episodes.length} 个字幕项目...`,
    type: 'info',
    duration: 0, // 不自动关闭
    showClose: true
  });

  try {
    // 优先尝试使用批量创建API
    if (episodes.length > 1) {
      try {
        const batchProjects: BatchCreateProjectItem[] = episodes.map(episode => ({
          episode_id: episode.episodeId.toString(),
          video_url: episode.videoUrl || '',
          languages: languages
        }));

        const response = await batchCreateProjects(batchProjects);

        loadingMessage.close();

        if (response.success_count > 0) {
          ElMessage.success(`${response.success_count} 个字幕项目已成功提交。请在项目状态页面查看进度。`);
        }

        if (response.failure_count > 0) {
          ElMessage.warning(`${response.failure_count} 个字幕项目提交失败。`);
          // 显示详细错误信息
          response.errors.forEach(error => {
            console.error(`剧集 ${error.episode_id} 创建失败:`, error.error);
          });
        }

        return;
      } catch (batchError) {
        console.warn('批量创建API失败，回退到并发创建:', batchError);
        // 如果批量API失败，回退到并发创建
      }
    }

    // 回退方案：使用并发创建（比逐个创建快）
    const requests = episodes.map(episode => ({
      requestFn: () => {
        const formData = new FormData();
        formData.append('episode_id', episode.episodeId.toString());
        if (episode.videoUrl) {
          formData.append('video_url', episode.videoUrl);
        }
        languages.forEach(lang => formData.append('languages', lang));
        return createProject(formData);
      },
      config: {
        url: '/taskapi/projects',
        method: 'POST' as const,
        retries: 2
      }
    }));

    const results = await requestManager.batchRequest(requests, {
      concurrency: Math.min(5, episodes.length), // 限制并发数为5或剧集数量
      failFast: false // 不因单个失败而终止
    });

    loadingMessage.close();

    const successCount = results.length;
    const failureCount = episodes.length - successCount;

    if (successCount > 0) {
      ElMessage.success(`${successCount} 个字幕项目已成功提交。请在项目状态页面查看进度。`);
    }

    if (failureCount > 0) {
      ElMessage.warning(`${failureCount} 个字幕项目提交失败。`);
    }

  } catch (error) {
    loadingMessage.close();
    console.error('批量创建项目失败:', error);
    ElMessage.error(`批量创建项目失败: ${error instanceof Error ? error.message : '未知错误'}，请重试。`);
  }
}

const handleSubmitRequest = async (data: any) => {
  await handleBatchProjectCreation(data.episodes, data.languages)
}

const handleSubmitRequestForEntireDrama = async (data: any) => {
  await handleBatchProjectCreation(data.episodes, data.languages)
}

// Initialize
onMounted(() => {
  store.setAvailableLanguages(props.availableLanguages)
})

// Expose methods for parent component
defineExpose({
  refreshDramas: () => {
    // This method will be handled by DramaListPanel
  },
  resetForm: () => {
    store.clearSelection()
  },
  clearEpisodeSelection: () => {
    store.clearSelection()
  }
})

</script>

<style src="./styles/common.css"></style>
<style scoped>
/* ==========================================================================
   统一设计系统 - 所有面板的基础样式
   ========================================================================== */

/* 主容器 - 优雅简洁 */
.subtitle-request-tab-container {
  padding: 16px;
  background: #f8fafc;
  height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
  display: flex;
  flex-direction: row;
  gap: 12px;
  overflow: hidden;
  box-sizing: border-box;
}

/* ==========================================================================
   统一面板容器 - 1:1:1比例布局
   ========================================================================== */
.panel-section {
  flex: 1;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(229, 231, 235, 0.8);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 32px);
  overflow: hidden;
}

.panel-section:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: rgba(59, 130, 246, 0.2);
}

/* 左中右面板特殊边框处理 */
.left-panel {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-right: none;
}

.middle-panel {
  border-radius: 0;
  border-left: none;
  border-right: none;
}

.right-panel {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: none;
}

/* ==========================================================================
   统一头部设计 - 所有面板头部一致
   ========================================================================== */
:deep(.panel-header) {
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 1px solid #e2e8f0;
  flex-shrink: 0;
  border-radius: 12px 12px 0 0;
}

:deep(.header-content) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

:deep(.header-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  letter-spacing: -0.025em;
}

:deep(.header-right) {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* ==========================================================================
   统一搜索和过滤区域
   ========================================================================== */
:deep(.drama-search-container) {
  padding: 16px 20px;
  background: #fafbfc;
  border-bottom: 1px solid #e2e8f0;
  flex-shrink: 0;
}

:deep(.drama-search-container .el-input) {
  border-radius: 8px;
  margin-bottom: 12px;
}

:deep(.drama-search-container .el-input__wrapper) {
  background: white;
  border: 1.5px solid #e2e8f0;
  transition: all 0.2s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

:deep(.drama-search-container .el-input__wrapper:hover) {
  border-color: #cbd5e1;
}

:deep(.drama-search-container .el-input__wrapper.is-focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* ==========================================================================
   统一表格设计 - 优雅简洁
   ========================================================================== */
:deep(.el-table) {
  border-radius: 0;
  font-size: 14px;
  height: 100% !important;
  border: none;
}

:deep(.el-table .el-table__body-wrapper) {
  max-height: none !important;
  overflow-y: auto;
}

:deep(.el-table::before) {
  display: none;
}

:deep(.el-table th.el-table__cell) {
  background: #f8fafc;
  color: #475569;
  font-weight: 600;
  font-size: 13px;
  border-bottom: 1px solid #e2e8f0;
  padding: 14px 12px;
  text-align: left;
}

:deep(.el-table td.el-table__cell) {
  border-bottom: 1px solid #f1f5f9;
  padding: 12px 12px;
  color: #334155;
}

:deep(.el-table__row) {
  cursor: pointer;
  transition: background-color 0.15s ease;
}

:deep(.el-table__row:hover > td.el-table__cell) {
  background-color: #f8fafc;
}

:deep(.el-table__row.current-row > td.el-table__cell) {
  background-color: #eff6ff;
  border-color: #dbeafe;
}

/* ==========================================================================
   统一内容区域
   ========================================================================== */
:deep(.episode-content),
:deep(.form-container) {
  flex: 1;
  overflow: hidden;
  background: white;
  min-height: 0;
}

:deep(.episode-table-section) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: hidden;
  min-height: 0;
}

:deep(.table-container) {
  flex: 1;
  overflow: hidden;
  min-height: 0;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  background: white;
}

/* ==========================================================================
   统一空状态设计
   ========================================================================== */
:deep(.empty-panel-container),
:deep(.empty-form-panel-container) {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

:deep(.el-empty) {
  padding: 40px 20px;
}

:deep(.el-empty__description) {
  color: #64748b;
  font-size: 15px;
  font-weight: 500;
}

/* ==========================================================================
   统一按钮和表单元素
   ========================================================================== */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  padding: 10px 20px;
  transition: all 0.2s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  border-color: #3b82f6;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border-color: #10b981;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
  border: 1.5px solid #e2e8f0;
  transition: all 0.2s ease;
}

:deep(.el-select .el-input__wrapper:hover) {
  border-color: #cbd5e1;
}

:deep(.el-select .el-input__wrapper.is-focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* ==========================================================================
   统一标签和状态指示器
   ========================================================================== */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
  font-size: 12px;
  padding: 4px 8px;
}

:deep(.total-count),
:deep(.selected-drama-info) {
  font-size: 12px;
  color: #64748b;
  background: #f1f5f9;
  padding: 4px 10px;
  border-radius: 14px;
  font-weight: 500;
  border: 1px solid #e2e8f0;
}

/* ==========================================================================
   统一分页设计
   ========================================================================== */
:deep(.drama-pagination-container) {
  padding: 16px 20px;
  background: #fafbfc;
  border-top: 1px solid #e2e8f0;
  flex-shrink: 0;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0 2px;
  font-weight: 500;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #f1f5f9;
  color: #3b82f6;
}

:deep(.el-pagination .el-pager li.active) {
  background: #3b82f6;
  color: white;
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
}

/* ==========================================================================
   统一滚动条设计
   ========================================================================== */
:deep(*)::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

:deep(*)::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

:deep(*)::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

:deep(*)::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* ==========================================================================
   分割线 - 精致简洁
   ========================================================================== */
.panel-divider {
  width: 2px;
  background: linear-gradient(180deg, rgba(226, 232, 240, 0.3) 0%, rgba(226, 232, 240, 0.8) 50%, rgba(226, 232, 240, 0.3) 100%);
  border: none;
  margin: 0;
  flex-shrink: 0;
  border-radius: 1px;
}

/* ==========================================================================
   响应式设计优化
   ========================================================================== */
@media (max-width: 1200px) {
  .subtitle-request-tab-container {
    padding: 12px;
    gap: 8px;
  }
  
  .panel-section {
    height: calc(100vh - 24px);
  }
}

@media (max-width: 768px) {
  .subtitle-request-tab-container {
    padding: 8px;
    flex-direction: column;
    height: auto;
    min-height: 100vh;
    gap: 8px;
  }
  
  .panel-section {
    height: auto;
    min-height: 350px;
    border-radius: 12px !important;
    margin-bottom: 8px;
  }
  
  .left-panel,
  .middle-panel,
  .right-panel {
    flex: none;
    border: 1px solid rgba(229, 231, 235, 0.8) !important;
    border-radius: 12px !important;
  }
  
  .panel-divider {
    width: 100%;
    height: 2px;
    margin: 4px 0;
  }
}
</style> 